package com.soulapp.hook.hooker

import android.content.Context
import android.view.LayoutInflater
import android.widget.Toast
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.highcapable.kavaref.KavaRef.Companion.resolve
import com.highcapable.kavaref.condition.type.Modifiers
import com.highcapable.yukihookapi.hook.core.YukiMemberHookCreator.MemberHookCreator.Result
import com.highcapable.yukihookapi.hook.factory.applyModuleTheme
import com.highcapable.yukihookapi.hook.log.YLog
import com.soulapp.data.ConfigData
import com.soulapp.hook.R
import com.soulapp.hook.databinding.DialogSelectDiceBinding

// 骰子猜拳游戏
object DiceRockGameHook : BaseHooker() {
    private const val TAG = "DiceRockGameHook"
    private var hook: Result? = null

    override fun getKey() = ConfigData.diceRockGame

    override fun onHook() {
        // cn.soulapp.imlib.msg.ImMessage.createChatSendMsg
        startHook()
    }

    override fun startHook() {
        YLog.debug("startHook $TAG $hookEnabled")
        if (!hookEnabled) return

        val className = "cn.soulapp.imlib.msg.chat.DiceFingerMsg"
        hook = className.toClass()
            .resolve()
            .optional()
            .constructor {
                modifiers(Modifiers.PUBLIC)
                parameters(Int::class.java)
            }.first()
            .hook {
                before {
                    // 获取调用栈
                    val stack = Thread.currentThread().stackTrace
                    val callerMethod = stack.find {
                        it.className == "cn.soulapp.android.component.chat.utils.d4"
                                && (it.methodName == "h1" || it.methodName == "y0")
                    }
                    if (callerMethod == null) {
                        return@before
                    }

                    when (callerMethod.methodName) {
                        "h1" -> {
                            // 猜拳 cn.soulapp.android.component.chat.utils.d4.h1
                            val rockValue = ConfigData.getInt(ConfigData.rockGameValue, 0)
                            if (rockValue == 0) {
                                // 随机
                                return@before
                            }
                            val showToast = ConfigData.getBoolean(ConfigData.showToast)
                            if (showToast) {
                                Toast.makeText(appContext, "猜拳作弊", Toast.LENGTH_SHORT).show()
                            }
                            args[0] = rockValue
                        }

                        "y0" -> {
                            // 骰子 cn.soulapp.android.component.chat.utils.d4.y0
                            val diceValue = ConfigData.getInt(ConfigData.diceGameValue, 0)
                            if (diceValue == 0) {
                                // 随机
                                return@before
                            }

                            val showToast = ConfigData.getBoolean(ConfigData.showToast)
                            if (showToast) {
                                Toast.makeText(appContext, "骰子作弊", Toast.LENGTH_SHORT).show()
                            }
                            args[0] = diceValue
                        }
                    }
                }
            }
    }

    fun showDiceDialog(context: Context) {
        // ✅ 使用 applyModuleTheme 包装 context，注入 AppCompat 主题
        val themedContext = context.applyModuleTheme(R.style.AppTheme)
        val binding = DialogSelectDiceBinding.inflate(LayoutInflater.from(themedContext))
        val dialogView = binding.root

        // 初始化猜拳
        val rockRadioGroup = binding.rockRadioGroup
        val randomOption = binding.randomOption

        val diceMap = mapOf(
            // 布
            R.id.paper_option to 1,
            // 剪刀
            R.id.scissors_option to 2,
            // 石头
            R.id.rock_option to 3
        )

        var rockValue = ConfigData.getInt(ConfigData.rockGameValue, 0)
        if (rockValue == 0) {
            randomOption.isChecked = true
        } else {
            diceMap.entries.find { it.value == rockValue }?.let {
                rockRadioGroup.check(it.key)
            }
        }
        // 猜拳 设置监听器
        randomOption.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                rockValue = 0
                rockRadioGroup.clearCheck()
            }
        }
        rockRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            if (checkedId == -1) {
                randomOption.isChecked = true
                rockValue = 0
                return@setOnCheckedChangeListener
            }
            randomOption.isChecked = false
            rockValue = diceMap[checkedId] ?: 0
        }

        // 初始化骰子
        val diceRadioGroup = binding.diceRadioGroup
        val diceRandom = binding.diceRandom
        val rockMap = mapOf(
            R.id.dice_one to 1,
            R.id.dice_two to 2,
            R.id.dice_three to 3,
            R.id.dice_four to 4,
            R.id.dice_five to 5,
            R.id.dice_six to 6
        )

        var diceValue = ConfigData.getInt(ConfigData.diceGameValue, 0)
        if (diceValue == 0) {
            diceRandom.isChecked = true
        } else {
            rockMap.entries.find { it.value == diceValue }?.let {
                diceRadioGroup.check(it.key)
            }
        }
        // 骰子 设置监听器
        diceRandom.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                diceValue = 0
                diceRadioGroup.clearCheck()
            }
        }
        diceRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            if (checkedId == -1) {
                diceRandom.isChecked = true
                diceValue = 0
                return@setOnCheckedChangeListener
            }

            diceRandom.isChecked = false
            diceValue = rockMap[checkedId] ?: 0
        }

        // 构建对话框
        MaterialAlertDialogBuilder(themedContext)
            .setTitle("作弊")
            .setView(dialogView)
            .setPositiveButton("确定") { dialog, _ ->
                ConfigData.putInt(ConfigData.rockGameValue, rockValue)
                ConfigData.putInt(ConfigData.diceGameValue, diceValue)
                dialog.dismiss()
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
            }
            .show()
    }

    // 重写clickListener属性并赋值
    override var clickListener: ((context: Context) -> Unit)? = { context ->
        showDiceDialog(context)
    }

    override fun stopHook() {
        if (hookEnabled) return
        hook?.let {
            it.remove {
                YLog.debug("stopHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook $TAG 失败")

    }

}